/* eslint-disable guard-for-in */
import React, { Component } from 'react';
import { Layout, Form, Row, Col, Table, Button, message } from 'antd';
import fetch from 'dva/fetch';
import moment from 'moment';
import styles from '../../../index.less';
import ShowType from '../../../routes/common/showType';
import * as config from '../../../utils/config';
import * as commonFunc from '../../Common/commonFunc';

const { Content } = Layout;
const FormItem = Form.Item;

class ReceiptComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      formData: props.formData,
      mainConfig: [],
      columns: [],
      data: [],
      dataOld: [],
      dataSave: [],
      dataSaveOld: [],
      width: 0,
      dBillMoneyValue: props.dBillMoney,
      gdsformconst: props.gdsformconst,
      addDisabled: true,
      saveDisabled: false,
      delDisabled: true,
      dBillMoney: '',
      sSettlementId: '',
      dOutMoney: '',
      sMemo: '',
      sBankId: '',
      sBankAccount: '',
      tDueDate: '',
      tPaymentDate: '',
      selectedRowKeys: [],
      delData: [],
      sActiveId: props.sActiveId,
      sId: props.sId,
      billnosetting: props.billnosetting,
      dateFormat: commonFunc.getDateFormat(props.app.systemData),
    };
  }

  componentWillMount() {
    const { dateFormat } = this.state;
    const mainData = {
      dBillMoney: this.props.dBillMoney,
      dOutMoney: this.props.dBillMoney,
      tPaymentDate: moment(new Date(), dateFormat),
    };
    const mainDataNew = {
      dBillMoney: this.props.dBillMoney,
      dOutMoney: this.props.dBillMoney,
      tPaymentDate: moment(new Date(), dateFormat),
    };
    this.setState({ mainData, mainDataNew });
    const { formData } = this.state;
    const wastebookConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'cahwastebook'))[0];
    const mainConfig = wastebookConfig.gdsconfigformslave;
    if (mainConfig !== undefined) {
      this.sqlData = [];
      const columns = [];
      let width = 0;
      mainConfig.forEach((child) => {
        if (child.bVisible) {
          columns.push({
            title: child.showName,
            dataIndex: child.sName,
            key: child.sName,
            width: child.iFitWidth,
            render: text => <span>{text}</span>,
          });
          width += child.iFitWidth;
        }
      });
      mainConfig.forEach((child) => {
        if (child.sName.substring(0, 1) === 's') {
          if (child.sDropDownType === 'sql') {
            const { token } = this.props.app;
            const { sActiveId } = this.state;
            const url = `${config.server_host}business/getSelectDataBysControlId/${child.sId}?sModelsId=${sActiveId}`;
            const values = {
              sKeyUpFilterName: '',
              sSqlCondition: '',
            };
            const options = {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                authorization: token,
              },
              body: JSON.stringify(values),
            };
            fetch(url, options).then(response => response.json()).then((json) => {
              if (json.code === 1) {
                const { rows } = json.dataset;
                this.sqlData.push({
                  sName: child.sName,
                  sqlData: rows,
                });
              } else {
                message.error(json.msg);
              }
            });
          }
        }
      });
      this.setState({
        width,
        columns,
        mainConfig,
        dBillMoney: mainConfig.filter(item => (item.sName.toLowerCase() === 'dbillmoney'))[0],
        sSettlementId: mainConfig.filter(item => (item.sName.toLowerCase() === 'ssettlementid'))[0],
        dOutMoney: mainConfig.filter(item => (item.sName.toLowerCase() === 'doutmoney'))[0],
        sMemo: mainConfig.filter(item => (item.sName.toLowerCase() === 'smemo'))[0],
        sBankId: mainConfig.filter(item => (item.sName.toLowerCase() === 'sbankid'))[0],
        sBankAccount: mainConfig.filter(item => (item.sName.toLowerCase() === 'sbankaccount'))[0],
        tDueDate: mainConfig.filter(item => (item.sName.toLowerCase() === 'tduedate'))[0],
        tPaymentDate: mainConfig.filter(item => (item.sName.toLowerCase() === 'tpaymentdate'))[0],
      });
    }
  }

  componentDidMount() {
    /* 获取数据 */
    const { formData, mainConfig, dateFormat } = this.state;
    const wastebookConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'cahwastebook'))[0];
    const wastebooksId = wastebookConfig.sId;
    const { sId, sActiveId } = this.state;
    const { token } = this.props.app;
    const value = {
      sSqlCondition: {
        sParentId: sId,
      },
    };
    const url = `${config.server_host}business/getBusinessDataByFormcustomId/${wastebooksId}?sModelsId=${sActiveId}`;
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const { dataSet } = json.dataset.rows[0];
        if (dataSet.length > 0) {
          const dataSave = [];
          const data = [];
          dataSet.forEach((child) => {
            let childSql = {};
            let childConst = {};
            for (const key in child) {
              const firstIndex = key.substring(0, 1);
              if (firstIndex === 't') {
                child[key] = moment(child[key]).format(dateFormat);
              } else if (firstIndex === 's') {
                const showConfig = mainConfig.filter(item => item.sName === key)[0];
                if (showConfig.sDropDownType === 'sql') {
                  const filterData = this.sqlData.filter(item => item.sName === key);
                  const sqlDatas = filterData[0].sqlData.filter(item => item.sId === child[key]);
                  if (sqlDatas.length > 0) {
                    childSql = { [key]: sqlDatas[0].showName };
                  }
                } else if (showConfig.sDropDownType === 'const') {
                  const showDropDown = JSON.parse(showConfig.showDropDown);
                  childConst = { [key]: showDropDown[child[key]] };
                }
              }
            }
            dataSave.push({
              ...child,
              key: child.sId,
            });
            data.push({
              ...child,
              ...childSql,
              ...childConst,
              key: child.sId,
            });
          });
          this.setState({
            data,
            dataOld: data,
            dataSave,
            dataSaveOld: dataSave,
            mainData: dataSave[dataSave.length - 1],
          });
        } else {
          this.handleAdd('initial');
        }
      } else {
        message.error(json.msg);
      }
    });
  }

  componentWillReceiveProps(nextProps) {
    const { systemData } = nextProps.app;
    const dateFormat = commonFunc.getDateFormat(systemData);
    this.setState({ dateFormat });
    const dBillMoneyValue = nextProps.dBillMoney;
    const { mainData, data } = this.state;
    mainData.dBillMoney = nextProps.dBillMoney;
    if (data.length > 0 && (data[data.length - 1].dOutMoney === undefined || data[data.length - 1].dOutMoney === '')) {
      mainData.dOutMoney = nextProps.dBillMoney;
    }
    const mainDataNew = {
      dBillMoney: nextProps.dBillMoney,
      dOutMoney: nextProps.dBillMoney,
      tPaymentDate: moment(new Date(), dateFormat),
    };
    this.setState({
      dBillMoneyValue,
      mainData,
      mainDataNew,
      dateFormat,
    });
  }

  handleFormChange = (value) => {
    const {
      mainData, data, dataSave, mainConfig, selectedRowKeys, dateFormat,
    } = this.state;
    const sName = Object.keys(value)[0];
    const showConfig = mainConfig.filter(item => item.sName === sName)[0];
    const { showDropDown, sDropDownType } = showConfig;
    let index;
    if (selectedRowKeys.length > 0) {
      index = data.findIndex(item => item.sId === selectedRowKeys[selectedRowKeys.length - 1]);
    } else {
      index = data.length - 1;
    }
    const child = data[index];
    if (dataSave[index].handleType === undefined) {
      dataSave[index] = { ...dataSave[index], ...value, handleType: 'update' };
    } else {
      dataSave[index] = { ...dataSave[index], ...value };
    }
    mainData[sName] = value[sName];
    const firstIndex = sName.substring(0, 1);
    if (firstIndex === 't') {
      data[index] = { ...child, [sName]: moment(value[sName]).format(dateFormat) };
    } else if (sDropDownType === 'const') {
      const key = value[sName];
      if (key === 'cash') {
        data[index].sBankId = '';
        dataSave[index].sBankId = '';
        mainData.sBankId = '';
      }
      const sValue = JSON.parse(showDropDown)[key];
      data[index] = { ...child, [sName]: sValue };
    } else if (sDropDownType !== 'sql') {
      data[index] = { ...child, ...value };
    }
    if (data[index].handleType === undefined) {
      data[index].handleType = 'update';
    }
    this.setState({
      mainData,
      data,
      dataSave,
    });
  };

  handleAdd = (type) => {
    /* 获取唯一Id */
    const { token } = this.props.app;
    const { mainDataNew, dateFormat } = this.state;
    const url = `${config.server_host}getUuid`;
    const options = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const key = json.dataset.rows[0];
        const {
          data, dataSave, dBillMoneyValue, sActiveId, sId,
        } = this.state;
        const newData = {
          key,
          sId: key,
          iOrder: data.length + 1,
          handleType: 'add',
          dBillMoney: dBillMoneyValue,
          dOutMoney: dBillMoneyValue,
          tPaymentDate: moment(new Date()).format(dateFormat),
          sType: '1',
          sFormId: sActiveId,
          sBillId: sId,
        };
        if (type === 'initial') {
          this.setState({
            dataOld: [...data, newData],
            dataSave: [...dataSave, newData],
          });
        }
        this.setState({
          data: [...data, newData],
          addDisabled: true,
          saveDisabled: false,
          mainData: { ...mainDataNew },
          dataSave: [...dataSave, newData],
          selectedRowKeys: [key],
        });
      } else {
        message.error(json.msg);
      }
    });
  };

  handleSubmitLocal = (e) => {
    e.preventDefault();
    this.form.validateFields((err) => {
      if (!err) {
        this.setState({
          dataOld: this.state.data,
          dataSaveOld: this.state.dataSave,
          addDisabled: false,
          saveDisabled: true,
          delDisabled: false,
        });
      }
    });
  };

  handleForm = (form) => {
    this.form = form;
  };

  handleCancel = () => {
    const { dataOld, dataSaveOld } = this.state;
    this.setState({
      data: dataOld,
      dataSave: dataSaveOld,
      addDisabled: false,
      saveDisabled: true,
      delDisabled: false,
      mainData: dataSaveOld[dataSaveOld.length - 1],
    });
  };

  handleSelectChange = (selectedRowKeys) => {
    const { dataSave } = this.state;
    const { length } = selectedRowKeys;
    const filterData = dataSave.filter(item => item.sId === selectedRowKeys[length - 1]);
    this.setState({
      selectedRowKeys,
      mainData: length === 0 ? dataSave[dataSave.length - 1] : filterData[0],
    });
  };

  handleDel = () => {
    const {
      selectedRowKeys, data, dataSave, mainDataNew,
    } = this.state;
    const { delData } = this.state;
    selectedRowKeys.forEach((child) => {
      const index = dataSave.findIndex(item => item.sId === child);
      if (index >= 0) {
        if (dataSave[index].handleType === undefined || dataSave[index].handleType === 'update') {
          delData.push({ ...dataSave[index], handleType: 'del' });
        }
        data.splice(index, 1);
        dataSave.splice(index, 1);
        if (dataSave.length === 0) {
          this.setState({ delData, selectedRowKeys: [] });
          this.handleAdd('initial');
        }
      }
    });
    this.setState({
      data,
      delData,
      mainData: dataSave.length > 0 ? dataSave[dataSave.length - 1] : mainDataNew,
      selectedRowKeys: [],
      dataSave,
    });
  };

  /* 非列表联动下拉 */
  handleSQLSelectChange = (value, dataType, dataName, recordRow, sName) => {
    const {
      mainData, selectedRowKeys, data, dataSave,
    } = this.state;
    let index;
    if (selectedRowKeys.length > 0) {
      index = data.findIndex(item => item.sId === selectedRowKeys[selectedRowKeys.length - 1]);
    } else {
      index = data.length - 1;
    }
    for (const item of value) {
      mainData[`${item.key}`] = item.value;
      data[index][`${item.key}`] = item.value;
      dataSave[index][`${item.key}`] = item.value;
    }
    if (sName === 'sBankId') {
      const obj = recordRow.split('-')[1];
      const showName = obj.split(':')[1];
      const child = data[index];
      data[index] = { ...child, [sName]: showName };
    }
    this.setState({ mainData, data, dataSave });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.form.validateFields((err) => {
      if (!err) {
        const {
          dBillMoneyValue, data, delData, dataSave,
        } = this.state;
        let dOutMoneyAll = 0;
        data.forEach((child) => {
          dOutMoneyAll += child.dOutMoney * 1;
        });
        if (dOutMoneyAll !== (dBillMoneyValue * 1)) {
          const { gdsformconst } = this.state;
          const filterData = gdsformconst.filter(item => item.sName === 'paymentTotalMoneyPop');
          if (filterData.length > 0) {
            return message.warning(filterData[0].showName);
          }
        }
        const { sActiveId } = this.state;
        const { token } = this.props.app;
        const url = `${config.server_host}business/addUpdateDelBusinessData?sModelsId=${sActiveId}`;
        const value = {
          data: [{
            sTable: 'cahwastebook',
            column: [...dataSave, ...delData],
          }],
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            const { billnosetting } = this.state;
            const bAutoCheck = billnosetting.bAutoCheck !== undefined ? billnosetting.bAutoCheck : false; /* 取窗体配置 */
            if (bAutoCheck) {
              this.props.onAutoCheck();
            } else {
              this.props.onClose();
            }
          } else {
            message.error(json.msg);
          }
        });
      }
    });
  };

  render() {
    const { pageLoading } = this.props;
    const { props, state } = this;
    return (
      <div>
        {pageLoading ? '' :
        <div>
          <CahReceiptComponent
            {...props}
            {...state}
            onAdd={this.handleAdd}
            onChange={this.handleFormChange}
            onSubmitLocal={this.handleSubmitLocal}
            onForm={this.handleForm}
            onCancel={this.handleCancel}
            onDel={this.handleDel}
            onSelectChange={this.handleSelectChange}
            onSubmit={this.handleSubmit}
            handleSelectChange={this.handleSQLSelectChange}
          />
        </div>}
      </div>
    );
  }
}

const CahReceiptComponent = Form.create({
  mapPropsToFields(props) {
    const { mainData, mainConfig } = props;
    const obj = commonFunc.mapPropsToFieldsChangeValue(mainConfig, mainData);
    return obj;
  },
  onValuesChange(props, changedFields) {
    props.onChange(changedFields);
  },
})((props) => {
  const {
    dBillMoney,
    sSettlementId,
    dOutMoney,
    sMemo,
    sBankId,
    sBankAccount,
    tDueDate,
    tPaymentDate,
    form,
    mainConfig,
    columns,
    data,
    width,
    onAdd,
    addDisabled,
    saveDisabled,
    delDisabled,
    handleSelectChange,
    onSubmitLocal,
    onForm,
    selectedRowKeys,
    onCancel,
    mainData,
    onDel,
    onSelectChange,
    onSubmit,
    onClose,
  } = props;
  const childProps = { form, handleSelectChange, onClose };
  const dBillMoneyProps = { showConfig: dBillMoney, ...childProps, disabled: true };
  const sSettlementIdProps = { showConfig: sSettlementId, ...childProps };
  const dOutMoneyProps = { showConfig: dOutMoney, ...childProps };
  const sMemoProps = { showConfig: sMemo, ...childProps };
  const sBankIdProps = { showConfig: sBankId, ...childProps };
  const sSettlementIdValue = mainData.sSettlementId !== undefined ? mainData.sSettlementId : '';
  if (sSettlementIdValue === 'bank') {
    sBankIdProps.disabled = false;
    sBankIdProps.showConfig.bNotEmpty = true;
  } else {
    sBankIdProps.disabled = true;
    sBankIdProps.showConfig.bNotEmpty = false;
  }
  const sBankAccountProps = { showConfig: sBankAccount, ...childProps };
  const tDueDateProps = { showConfig: tDueDate, ...childProps };
  const tPaymentDateProps = { showConfig: tPaymentDate, ...childProps };
  let reserveContent = '';
  if (Object.keys(mainConfig).length > 0) {
    reserveContent = commonFunc.Reserve(mainConfig, childProps);
  }
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  return (
    <Form>
      <Layout>
        <Content className={styles.contentPop}>
          {onForm(form)}
          <FormItem>
            <Row type="flex">
              <Col
                span={6}
                order={dBillMoney.iOrder > 24 ? 24 : dBillMoney.iOrder}
                style={{ display: dBillMoney.bVisible ? 'block' : 'none' }}
              >
                <ShowType sName="dBillMoney" showDefaultName="单据金额" {...dBillMoneyProps} />
              </Col>
              <Col
                span={6}
                order={sSettlementId.iOrder > 24 ? 24 : sSettlementId.iOrder}
                style={{ display: sSettlementId.bVisible ? 'block' : 'none' }}
              >
                <ShowType sName="sSettlementId" showDefaultName="结算类型" {...sSettlementIdProps} />
              </Col>
              <Col
                span={6}
                order={dOutMoney.iOrder > 24 ? 24 : dOutMoney.iOrder}
                style={{ display: dOutMoney.bVisible ? 'block' : 'none' }}
              >
                <ShowType sName="dOutMoney" showDefaultName="出账金额" {...dOutMoneyProps} />
              </Col>
              <Col
                span={6}
                order={sMemo.iOrder > 24 ? 24 : sMemo.iOrder}
                style={{ display: sMemo.bVisible ? 'block' : 'none' }}
              >
                <ShowType sName="sMemo" textArea showDefaultName="备注" {...sMemoProps} />
              </Col>
              <Col
                span={6}
                order={sBankId.iOrder > 24 ? 24 : sBankId.iOrder}
                style={{ display: sBankId.bVisible ? 'block' : 'none' }}
              >
                <ShowType sName="sBankId" showDefaultName="银行名称" {...sBankIdProps} />
              </Col>
              <Col
                span={6}
                order={sBankAccount.iOrder > 24 ? 24 : sBankAccount.iOrder}
                style={{ display: sBankAccount.bVisible ? 'block' : 'none' }}
              >
                <ShowType sName="sBankAccount" showDefaultName="银行账号" {...sBankAccountProps} />
              </Col>
              <Col
                span={6}
                order={tDueDate.iOrder > 24 ? 24 : tDueDate.iOrder}
                style={{ display: tDueDate.bVisible ? 'block' : 'none' }}
              >
                <ShowType sName="tDueDate" showDefaultName="票据到期日期" {...tDueDateProps} />
              </Col>
              <Col
                span={6}
                order={tPaymentDate.iOrder > 24 ? 24 : tPaymentDate.iOrder}
                style={{ display: tPaymentDate.bVisible ? 'block' : 'none' }}
              >
                <ShowType sName="tPaymentDate" showDefaultName="实际收款日" {...tPaymentDateProps} />
              </Col>
              {reserveContent}
            </Row>
          </FormItem>
          <Table
            bordered
            size="middle"
            scroll={{ x: width }}
            className={styles.tableShow}
            columns={columns}
            dataSource={data}
            rowSelection={rowSelection}
            pagination={false}
          />
          <div className={styles.buttonOpt}>
            <Button onClick={onSubmit}>确定</Button>
            <Button onClick={onAdd} disabled={addDisabled}>添加</Button>
            <Button onClick={onSubmitLocal} disabled={saveDisabled}>保存</Button>
            <Button onClick={onCancel} disabled={saveDisabled}>取消</Button>
            <Button onClick={onDel} disabled={delDisabled}>删除</Button>
          </div>
        </Content>
      </Layout>
    </Form>
  );
});


export default ReceiptComponent;
